<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Code1024 - JS-canvas-Trial</title>
</head>
<body>
<div>
	<h4>主体代码</h4>
	<p>
		说明： <br />
		参数： x, y；值为 0-1023 间（含）的整数<br />
		返回： r, g, b, a；变量已初始化为 0，返回值应为 0-255 间（含）的整数<br />
	</p>
	<p>
<textarea id="code" rows="12" cols="120">
// sample code

var x0=x-512,y0=512-y,precision=1.41421;
if (y0==0 || x0==0
	|| (y0%64 == 0 && x0 > 0 && x0 < 8)
	|| (x0%64 == 0 && y0 > 0 && y0 < 8)
	)
	r=g=b=255;

if (Math.abs(y0 - x0*x0/512) < precision) r=255;
</textarea>
	</p>
	<p>
		<input type="button" value="运行" onclick="run_code()" />
		&nbsp;&nbsp;
		<span id="tips"></span>
	</p>
</div>
<div>
	<canvas id="canvas1024"></canvas>
</div>
<div id="func_tpl" style="display:none;">
function get_color_at(x, y) {
	var r = 0, g = 0, b = 0, a = 0;
{{code}}
	return [r, g, b, a];
}
</div>
<script type="text/javascript">
<!--
	/**
	 * 获取指定点的颜色值： r,g,b,alpha
	 * 坐标范围： (0, 0) => (1023, 1023)
	 * 颜色值范围：均为 0 - 255
 	 * 透明度： 0 - 255， 值越大越透明
	 */
	function get_color_at(x, y) {
		var r = 0, g = 0, b = 0, a = 0;

		// {{code start}}
		// your code here

		// {{code end}}

		return [r, g, b, a];
	}

	/**
	 * 根据 id 获取元素
	 */
	function _id(elemId) {
		return document.getElementById(elemId);
	}

	/**
	 * 在 canvas 上绘制图案
	 */
	function draw1024() {
		var canvas = _id("canvas1024");
		var width = 1024, height = 1024;
		canvas.width = width;
		canvas.height = height;
		var context = canvas.getContext("2d");
		context.fillRect(0, 0, width, height);


		var imgData = context.getImageData(0, 0, width, height);
		var rgb, idx = 0;
		for (y = 0; y < height; y++){
			for (x = 0; x < width; x++){
				rgb = get_color_at(x, y);
				imgData.data[idx++] = rgb[0]&255;
				imgData.data[idx++] = rgb[1]&255;
				imgData.data[idx++] = rgb[2]&255;
				imgData.data[idx++] = parseInt(255*(1-rgb[3]/255));
			}
		}
		context.putImageData(imgData, 0, 0);
	}

	/**
	 * 运行代码，绘制 canvas
	 */
	function run_code() {
		var oTips = _id('tips');
		oTips.innerHTML = "开始运行~~";

		var inputCode = _id('code').value;
		var funcCode = _id('func_tpl').innerHTML.replace('{{code}}', inputCode);

		runScript(funcCode);
		oTips.innerHTML = "函数加载完成，开始绘制~~";

		draw1024();
		oTips.innerHTML = "绘制完毕！";
		setTimeout(function() {
			oTips.innerHTML = "";
		}, 2000);
	}

	/**
	 * runScript
	 * 动态运行 js 代码
	 */
	function isIE() {
		var client_pc = navigator.userAgent.toLowerCase();
		return (client_pc.indexOf("msie") != -1) && (client_pc.indexOf("opera") == -1);
	}
	function runScript(code){
		var elem = document.createElementNS ?
				document.createElementNS('http://www.w3.org/1999/xhtml', "script") :
				document.createElement("script");
		elem.type = "text/javascript";
		if( isIE() ){// IE
			elem.text = code;
		} else {
			elem.appendChild((document.createTextNode(code)));
		}
		document.getElementsByTagName("head")[0].appendChild(elem);
	}
//-->
</script>
</body>
</html>
